﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Web;
using System.ServiceModel.DomainServices.EntityFramework; 
using Domain.Abstract;
using Domain.Entity;

namespace Domain.Concrete
{
    public class EFReviewRepository : IReviewRepository
    {
        public EFDbContext Context { get; set; }

        public EFReviewRepository()
        {
            Context = EFDbContext.Instance;
        }

        public EFReviewRepository(EFDbContext context)
        {
            Context = context;
        }

        public IQueryable<Review> Reviews
        {
            get { return Context.Reviews; }
        }

        public void SaveReview(Review review)
        {
            if (review.Id == 0)
            {
                Context.Reviews.Attach(review);
                Context.Entry(review).State = EntityState.Added;
            }
            else
            {
                Review dbReview = this.FindReview(review.Id);
                dbReview.FileName = review.FileName;
                dbReview.Summary = review.Summary;
                dbReview.Message = review.Message;
                dbReview.Name = review.Name;
                dbReview.YoutubeLink = review.YoutubeLink;
                Context.Entry(dbReview).State = EntityState.Modified;
            }
            Context.SaveChanges();

        }

        public void DeleteReview(Review review)
        {
            var dbReview = Context.Reviews.SingleOrDefault(x => x.Id == review.Id);

            if (dbReview != null)
            {
                Context.Reviews.Remove(dbReview);
            }
            Context.SaveChanges();
        }

        public Review FindReview(int id)
        {
            return Reviews.FirstOrDefault(x => x.Id == id);
        }

        public bool IsFeedbackInReview(int reviewId, int feedbackId)
        {
            Review review = this.FindReview(reviewId);

            Feedback feedback = null;

            if (review != null)
            {
                feedback = review.Feedbacks.FirstOrDefault(f => f.Id == feedbackId);
            }

            return feedback != null;
        }
    }
}
